package com.cgly.medical.service.impl;

import com.cgly.medical.entity.AccountModel;
import com.cgly.medical.mapper.AccountMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @program: medical
 * @description:UserDetailsService：用户信息存在哪里（数据库、TXT）用户来源
 * @author: chen di
 * @create: 2022-08-15 15:54
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    AccountMapper accountMapper;


    public AccountModel findByName(String username){
        return (AccountModel) accountMapper.securityLogin(username);
    }

    //查询数据库
    @Override
    public AccountModel loadUserByUsername(String username) throws UsernameNotFoundException {
        AccountModel user = this.findByName(username);
        System.out.println(user.getAuthorities());
        System.out.println(user.getUtype());
//        AccountModel accountModel = new AccountModel(username,user.getPwd(),user.getSalt(),AuthorityUtils.commaSeparatedStringToAuthorityList(user.getUtype()));
        user.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(user.getUtype()));
        return user;
    }



//    public String query


//    /**
//     * 查询用户数据，返回用户表信息（AccountModel 是 UserDetails 的实现类）给 security
//     * @param username
//     * @return
//     * @throws UsernameNotFoundException
//     */
//    @Override
//    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        AccountModel accountModel = accountMapper.securityLogin(username);//根据username查数据库
////        AccountModel accountModel = new AccountModel();
//        // 判断用户是否存在
//        if (accountModel == null) {
//            throw new UsernameNotFoundException("用户不存在");
//        }
//
//        //数据库格式通常为 ROLE_xx1，ROLE_xx2
//        String role = accountModel.getUtype();
//        // AuthorityUtils：security提供的逗号工具类，将 role 划分为权限集
//        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList(role);
//        System.out.println(accountModel.getRealname());
//        AccountModel accountModel1 = new AccountModel(
//                accountModel.getId(),
//                accountModel.getUrealName(),
//                accountModel.getUname(),
//                accountModel.getPwd(),
//                accountModel.getSalt(),
//                accountModel.getPhonenumber(),
//                role,
//                accountModel.getEmail(),
//                auths
//                );
//        return accountModel1;
//    }
}